/**
 * Created by artheru on 2017/1/23.
 */

import events from "./events";
import storage from "./storage";
//import request from "request";

var request = require("request");

function tokenify(token) {
    return new Promise(function (resolve, reject) {
        request("http://test.utbon.com/api/im/tokenify.ashx?token="+ token, function (error, res, body) {
            try {
                if (!error && res.statusCode == 200) {
                    let uid = JSON.parse(body).uid;
                    if (!uid) reject(body);
                    resolve(uid);
                } else {
                    reject(e)
                }
            }catch(e){
                reject(e)
            }
        });
    });
}

module.exports = function startIMServer(ctx) {
    console.log("IMServer Starting...");

    let io = ctx.io.of("message").on("connection", function (socket) {
        let uid;
        console.log("connected ", socket.id);


        function wrap(fn) {
            return (...args) => fn(...args).catch(e => {
                console.log("error", e);
                socket.emit("failure", e);
            });
        }

        socket.on("logoff", function () {
            events.unregister("onmessage", "listener:" + uid);
        });

        socket.on("disconnect", function () {
            events.unregister("onmessage", "listener:" + uid);
        });

        socket.on("authentication", wrap(async function (token, cb) {
            let uid = await tokenify(token);
            console.log("authenticated:", uid);
            socket.emit("tokenified", uid);

            events.register((message) => socket.emit("message", message), "onmessage", "listener:" + uid);

            if (cb) cb();

            socket.on("send", wrap(async(message, cb) => {
                let saveMsg = await storage.push({
                    from: uid,
                    to: message.to,
                    messageType: message.messageType,
                    messageContent: message.messageContent,
                });
                events.emit(saveMsg, "onmessage", "listener:" + message.to);
                cb({mid: saveMsg.mid});
                //console.log(saveMsg);
            }));
            socket.on("pullConversation", wrap(async(opt, cb) => {
                //console.log("pulling...");
                let ls = await storage.pullConversation(uid, opt.otherParty, opt.fromMid);
                cb(ls);
            }));
            socket.on("listConversations", wrap(async(empty, cb) => {
                //console.log("listing...");
                let ls = cb(await storage.listConversations(uid));
                cb(ls);
            }));
            socket.on("clearUnread", wrap(async(otherParty) => {
                console.log("clear chat unread:", otherParty);
                await storage.clearUnread(uid, otherParty);
            }));
            //setInterval(()=>{onMessage({from:7,to:uid,messageType:"text",messageContent:"hello world", time:(new Date()).toString()})}, 3000);
        }));

    });

    async function sendMessage(msg) {
        let saveMsg = await storage.push(msg);
        events.emit(saveMsg, "onmessage", "listener:" + msg.to);
        return saveMsg;
    }

    return {
        sendMessage
    }
}
